// 对于axios进行二次封装
import axios from "axios";
import nprogress from 'nprogress';
import 'nprogress/nprogress.css';
import { ElMessage } from 'element-plus'

const requests = axios.create({
	baseURL:'/api', //请求基本路径
	timeout:5000 //超时时间
})

//请求拦截器
requests.interceptors.request.use((config)=>{
    nprogress.start()
	if (localStorage.getItem('token')) {
        config.headers.Authorization = localStorage.getItem('token')
    }
    return config
}, error => {
    return Promise.reject(error)
})

// 响应拦截器
requests.interceptors.response.use(
	(res)=>{ //响应成功的回调
	nprogress.done() //进度条停止
		return res.data;
	},
	//响应失败的回调
	(error)=>{
		if (status == 401) {
			ElMessage.error('The token is invalid, please log in again')
			// 清除token
			localStorage.removeItem('token')
			// 重新跳转到login页面
			router.push('/login')
		}	
		return Promise.reject(new Error('failed'))
		}
)

export default requests;




